"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const http = tslib_1.__importStar(require("http"));
const path = tslib_1.__importStar(require("path"));
const Url = tslib_1.__importStar(require("url"));
const address_1 = require("address");
const http_1 = require("./helper/http");
const worker_1 = tslib_1.__importDefault(require("./worker"));
const utils_1 = require("./helper/utils");
exports.default = async (options) => {
    if (!options.dir) {
        await utils_1.logError('start', 'error', '缺少dir参数');
        return null;
    }
    if (!path.isAbsolute(options.dir)) {
        await utils_1.logError('start', 'error', 'dir参数必须是绝对路径');
        return null;
    }
    const DIR = options.dir;
    const SECRET = options.secret;
    const PORT = await http_1.getPort(options.port);
    const WORKER = worker_1.default();
    const URL_PATH = options.path || '/webhook';
    http.createServer(async (req, res) => {
        try {
            if (req.method !== 'POST' || Url.parse(req.url || '').pathname !== URL_PATH)
                return http_1.notFound(res);
            const result = await http_1.getHookData(req, SECRET);
            if (result.status) {
                const body = result.body;
                const repo = body.repository;
                const repoName = repo.name;
                // gitlab的属性名为 git_http_url 和 git_ssh_url
                const httpUrl = repo.clone_url || repo.git_http_url;
                const sshUrl = repo.ssh_url || repo.git_ssh_url;
                const tag = body.ref.match(/(v(\d+\.)+\d+)$/)[1];
                WORKER.send({
                    options: Object.assign(Object.assign({}, options), { httpUrl, sshUrl }),
                    REPO_NAME: repoName,
                    TAG: tag,
                    REPO_ROOT: DIR,
                    ROOT: __dirname,
                });
                res.statusCode = 200;
                res.end('successed.');
                return;
            }
            res.end('ok');
        }
        catch (err) {
            http_1.notFound(res, err.message);
        }
    })
        .listen(PORT)
        .on('listening', async () => {
        const info = ['Webhook配置的地址：',
            `局域网： http://${address_1.ip()}:${PORT}${URL_PATH}`,
            `外网：   http://[外网ip]:${PORT}${URL_PATH}`].join('\n');
        if (options.daemon && process.send) {
            process.send(info);
        }
        else {
            console.log(info);
        }
    })
        .on('error', console.error);
    return WORKER;
};
